package com.txazo.service.impl;

import java.sql.Connection;
import java.util.List;

import com.txazo.dao.BaseDao;
import com.txazo.dao.factory.DaoFactory;
import com.txazo.domain.User;
import com.txazo.service.UserService;
import com.txazo.util.ConnectionUtil;

/**
 * 用户模块Service实现
 * 
 * @author txazo
 * @since 1.0
 * 
 */
public class UserServiceImpl implements UserService {

	@Override
	public User login(User user) {
		Connection connection = ConnectionUtil.getConnection();
		BaseDao baseDao = DaoFactory.getBaseDao(connection);
		try {
			List<User> list = baseDao.executeQuery(
					"select * from user where username = ? and password = ?",
					User.class, new Object[] { user.getUsername(),
							user.getPassword() });
			if (list.size() == 1) {
				return list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (baseDao.getPreparedStatement() != null)
					baseDao.getPreparedStatement().close();
				if (connection != null)
					connection.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public User register(User user) {
		Connection connection = ConnectionUtil.getConnection();
		BaseDao baseDao = DaoFactory.getBaseDao(connection);
		try {
			connection.setAutoCommit(false);

			List<User> list = baseDao.executeQuery(
					"select * from user where username = ?", User.class,
					new Object[] { user.getUsername() });
			if (list.size() == 0) {
				baseDao
						.executeUpdate(
								"insert into user(username, password) values(?, ?)",
								new Object[] { user.getUsername(),
										user.getPassword() });
				connection.commit();

				return baseDao.executeQuery(
						"select * from user where username = ?", User.class,
						new Object[] { user.getUsername() }).get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				connection.rollback();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (baseDao.getPreparedStatement() != null)
					baseDao.getPreparedStatement().close();
				if (connection != null)
					connection.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
